package com.heitian.ssm.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.heitian.ssm.controller.AttachController;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通用工具类
 * Created by a1278 on 17/5/7.
 */
public class CommonUtils {

    /**
     * 获取uuid
     *
     * @return
     */
    public static String GetUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 生成MD5的工具类
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("md5生成失败");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16位的MD5

        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        return df.format(new Date());
    }

    /**
     * 拼接返回的json数据
     * @param message
     * @return
     */
    public static JsonObject createJson(String code,String message,String UserArea) {
        JsonObject jsonObject = new JsonObject();
        JsonObject ReturnInfoJson = new JsonObject();
        ReturnInfoJson.addProperty("Code", "1");
        ReturnInfoJson.addProperty("Description", "");
        jsonObject.add("ReturnInfo", ReturnInfoJson);
        JsonObject BusinessInfoJson = new JsonObject();
        BusinessInfoJson.addProperty("Code", code);
        BusinessInfoJson.addProperty("Description", message);
        jsonObject.add("BusinessInfo", BusinessInfoJson);

        if(UserArea!=null){
            jsonObject.add("UserArea", new JsonParser().parse(UserArea).getAsJsonObject());
        }
        return jsonObject;
    }

    /**
     * 获取验证
     * @return
     */
    public static String getMobileToken() {
        return "Epoint_WebSerivce_**##0601";
    }

    /***
     * 解码base64的数据
     * @param input
     * @return
     * @throws Exception
     */
    public static byte[] decodeBase64(String input) throws Exception{
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod= clazz.getMethod("decode", String.class);
        mainMethod.setAccessible(true);
        Object retObj=mainMethod.invoke(null, input);
        return (byte[])retObj;
    }

    /**
     * base64编码数据
     * @param input
     * @return
     * @throws Exception
     */
    public static String encodeBase64(byte[]input) throws Exception{
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod= clazz.getMethod("encode", byte[].class);
        mainMethod.setAccessible(true);
        Object retObj=mainMethod.invoke(null, new Object[]{input});
        return (String)retObj;
    }

    /**
     * 从请求中获取json数据
     * @param request
     * @return
     * @throws IOException
     */
    public static JsonObject getJson(HttpServletRequest request) throws IOException {
        StringBuffer buffer = new StringBuffer();
        String line = null;
        BufferedReader reader = request.getReader();
        while((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        JsonObject json =  new JsonParser().parse(buffer.toString()).getAsJsonObject();
        String ValidateData = json.get("ValidateData").getAsString();
        if(getMobileToken().equals(ValidateData)){
            return json.get("paras").getAsJsonObject();
        }
        return null;
    }

    /**
     * @author I321533
     * @param json
     * @param clazz
     * @return
     */
    public static <T> List<T> jsonToList(String json, Class<T[]> clazz)
    {
        Gson gson = new Gson();
        T[] array = gson.fromJson(json, clazz);
        return Arrays.asList(array);
    }

    /**
     * @param json
     * @param clazz
     * @return
     */
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz)
    {
        Type type = new TypeToken<ArrayList<JsonObject>>()
        {}.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> arrayList = new ArrayList<T>();
        for (JsonObject jsonObject : jsonObjects)
        {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

    /**
     * 包装list的数据
     * @param list
     * @return
     */
    public static String setUserAreaListStr(List list){
        Gson gson = new Gson();
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("list",gson.toJsonTree(list));
        return jsonObject.toString();
    }

}

